<template>
  <view>
    <u-navbar
      :title="customTitle"
      :auto-back="autoBack"
      :border="border"
      :bg-color="bcolor"
      :placeholder="occupy"
      :title-style="{ color: tcolor }"
    >
      <template slot="left">
        <slot name="left" />
      </template>
      <template slot="right">
        <slot name="right" />
      </template>
    </u-navbar>
  </view>
</template>

<script>
export default {
  props: {
    // 页面标题（H5不填写则获取pages.json中配置的名称）
    title: {
      type: String,
      default: "",
    },
    // 标题背景色（默认透明）
    bgColor: {
      type: String,
      default: "transparent",
    },
    // 允许返回
    autoBack: {
      type: Boolean,
      default: true,
    },
    // 开启占位高度
    occupy: {
      type: Boolean,
      default: false,
    },
    // 文字颜色
    color: {
      type: String,
      default: "#fff",
    },
    // 禁止滚动改色
    disabled: {
      type: Boolean,
      default: false,
    },
    // 下边框
    border: {
      type: Boolean,
      default: false,
    },
    /**
     * 滚动改变颜色距离 （须在父组件配置如下：）
     *  onPageScroll(scroll) {
     *    uni.$emit("onPageScroll", scroll.scrollTop);
     *  },
     */
    scrollTop: {
      type: [String, Number],
      default: 140,
    },
    // 滚动后背景色
    scrollBgColor: {
      type: String,
      default: "#fff",
    },
    // 滚动后文字颜色
    scrollColor: {
      type: String,
      default: "#222",
    },
  },
  data() {
    return {
      customTitle: "", // 标题内容
      bcolor: "", // 背景色
      tcolor: "", // 文字色
    };
  },
  mounted() {
    this.init();
    uni.$on("onPageScroll", (top) => {
      if (this.disabled) return;
      if (parseInt(top) > parseInt(this.scrollTop)) {
        this.bcolor = this.scrollBgColor;
        this.tcolor = this.scrollColor;
      } else {
        this.bcolor = this.bgColor;
        this.tcolor = this.color;
      }
    });
  },
  methods: {
    // 处理导航栏信息
    init() {
      if (this.title) {
        this.customTitle = this.title;
      } else {
        var pages = getCurrentPages();
        var page = pages[pages.length - 1];
        var title = "";
        // #ifndef MP-WEIXIN
        title = page.$holder.navigationBarTitleText;
        this.customTitle = title;
        // #endif
      }
      this.bcolor = this.bgColor;
      this.tcolor = this.color;
    },
  },
  onUnload() {
    // 移除监听事件
    uni.$off("onPageScroll");
  },
};
</script>

<style lang="scss" scoped></style>
